package app.security;

import app.models.system.Resource;
import app.models.system.Role;
import app.models.system.User;
import com.ifonly.security.IfonlySecurity;
import com.ifonly.security.PermissionValidationHandler;
import com.ifonly.security.SecurityEntry;
import com.ifonly.security.SecurityInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ifonly
 * @version 1.0 2016-01-28 17:42
 * @since JDK 1.6
 */
public class DefaultAppPermissionValidator implements PermissionValidationHandler.IPermissionValidator {

    private static List<String> EXCLUDES = new ArrayList<String>() {
        private static final long serialVersionUID = 6923342987855410357L;

        {
            add("/logout");
            add("/login");
            add("/druid");
            add("/file/upload");
            add("/file/delete");
            add("/file/render");
        }
    };

    @Override
    public boolean validate(String target) {
        Subject subject = SecurityUtils.getSubject();
        if (EXCLUDES.contains(target) || target.contains(".")) {
            return true;
        }

        if(subject.isAuthenticated() || subject.isRemembered()) {
            SecurityEntry<Long, SecurityInfo<User, Role, List<Resource>>> securityEntry = IfonlySecurity.getSecurityEntry();
            SecurityInfo<User, Role, List<Resource>> info = securityEntry.getInfo();
            List<Resource> resources = info.getP();
            boolean ok = false;
            for (Resource resource: resources) {
                List<Resource> children = (List<Resource>) resource.get("children");
                if (children != null && !children.isEmpty()) {
                    for (Resource child: children) {
                        String url = child.getString("url");
                        if (target.contains(url) || (target + "/").contains(url)) {
                            ok = true;
                            break;
                        }
                    }
                } else {
                    String url = resource.getString("url");
                    if (target.contains(url)) {
                        ok = true;
                        break;
                    }
                }
            }
            return ok;
        }

        return true;
    }

}
